package com.cn.delan.core.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
 * 类操作工具类，包含了反射相关操作
 * @author BingGo
 *
 */
public class ClassUtil {
	/**
	 * 调用无参数的构造函数初始化类
	 * @param clazz 类
	 * @return 返回此类的对象
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static <T> T create(Class<T> clazz) throws InstantiationException, IllegalAccessException{
		Object obj = clazz.newInstance();
		return clazz.cast(obj);
	}
	/**
	 * 调用带参数的构造函数初始化类
	 * @param clazz 类
	 * @param args 构造函数中的参数
	 * @return 返回此类的对象
	 * @throws IllegalArgumentException
	 * @throws SecurityException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static <T> T create(Class<T> clazz,Object [] args) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		Class<?>[] type = ClassUtil.getClass(args);
		return clazz.getConstructor(type).newInstance(args);
	}
	/**
	 * 执行对象的指定方法
	 * @param obj 对象
	 * @param methodName 方法名
	 * @param args 调用方法所用的参数
	 * @return 该方法的返回值
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static Object invoke(Object obj,String methodName,Object [] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		Method method = obj.getClass().getMethod(methodName, ClassUtil.getClass(args));
		return method.invoke(obj, args);
	}
	/**
	 * 执行对象的setName方法对对name参数进行赋值
	 * @param obj 对象
	 * @param name 需要赋值的属性名
	 * @param value 值
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws NoSuchMethodException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	public static void set(Object obj,String name,Object value) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException{
		String setMethodName = "set"+name.trim().substring(0,1).toUpperCase()+name.substring(1);
		ClassUtil.invoke(obj, setMethodName, new Object[]{value});
	}
	/**
	 * 根据参数数组获取对应的类型数组
	 * @param args 参数数组
	 * @return 类型数组
	 */
	private static Class<?>[] getClass(Object[] args){
		Class<?>[] type = new Class<?>[args.length];
		for(int i=0;i<args.length;i++){
			type[i] = args[i].getClass();
		}
		return type;
	}

}
